package com.xunsiya.service.system;

import com.xunsiya.common.config.util.ConstantInfo;
import com.xunsiya.system.dao.AuthMapper;
import com.xunsiya.system.dao.CompanyMapper;
import com.xunsiya.system.dao.UserMapper;
import com.xunsiya.system.vo.Company;
import com.xunsiya.system.vo.User;
import com.xunsiya.tools.common.msg.Msg;
import com.xunsiya.tools.common.pagination.ForePage;
import com.xunsiya.tools.common.pagination.PagedUtil;
import com.xunsiya.tools.common.string.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 用户实现层
 *
 * @author linqy
 * @version 1.0
 *          <p/>
 *          <br/>
 *          <br/>修订人    修订时间      描述信息
 *          <br/>-----------------------------------------------------
 *          <br/>linqy    2017/11/11    初始创建
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AuthMapper authMapper;

    @Autowired
    private CompanyMapper companyMapper;

    /**
     * 删除用户
     * @param id
     * @return
     */
    public Msg deleteUser(int id) {
        User user = new User();
        user.setId(id);
        List<User> list = userMapper.queryUser(user);
        if (list == null || list.size() == 0) {
            return new Msg(true, "删除失败,用户不存在!");
        }
        user = list.get(0);
        userMapper.deleteUser(id);
        //删除权限数据
        authMapper.deleteUserAuth(id);
        return new Msg(true, "删除成功!", user);
    }

    /**
     * 增加用户
     * @param user
     * @return
     */
    public Msg insertUser(User user) {
        //检查重复
        int count = userMapper.queryUserName(user.getUserName(), -1);
        if (count > 0) {
            return new Msg(false, "用户名不能重复");
        }
        userMapper.insertUser(user);
        return new Msg(true, "操作成功!");
    }

    /**
     * 修改用户
     * @param user
     * @return
     */
    public Msg modifyUser(User user) {
        if(user.getId() != null)
        {
            //查询原用户信息
            User userOld = userMapper.queryById(user.getId());
            if (userOld == null) {
                return new Msg(false, "操作失败,用户不存在!");
            }
            if (!userOld.getUserName().equals(user.getUserName())) {
                //校验新用户名是否重复
                int num = userMapper.checkName(user.getUserName(), user.getId());
                if (num > 0) {
                    return new Msg(false, "用户名不能重复!");
                }
            }
        }
        userMapper.modifyUser(user);
        return new Msg(true, "操作成功!");
    }

    public List<User> queryUser(User user) {
        if (user != null) {
            return userMapper.queryUser(user);
        }
        return null;
    }
    /**
     * 根据用户名查询用户
     * @param userName
     * @return
     */
    public User queryUserByUserName(String userName) {
        return userMapper.queryUserByUserName(userName);
    }

    /**
     * 查询用户
     * 非管理员登录后只能看到所有下级群组的用户
     * @param user
     * @param pageIndex
     * @param pageSize
     * @return
     */
    public Msg queryFilterUserForPage(User user, int pageIndex, int pageSize) {
        //根据用户获取所在群组的所有下级群组
        if (!ConstantInfo.PLATFORM_COPMANY_ID.equals(user.getCompanyId())) {
            List<Company> companyList = companyMapper.getCompanyByUser(user.getCompanyId());
            if (CollectionUtils.isEmpty(companyList)) {
                return new Msg(true, "");
            }
            List<Integer> companyIdList = new ArrayList<>();
            for(Company cp : companyList)
            {
                companyIdList.add(cp.getId());
            }
            user.setSubCompanyIdList(companyIdList);
        }
        int count = userMapper.queryFilterUserCount(user);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<Map<String, Object>> l = userMapper.queryFilterUserForPage(user, PagedUtil.getStartIndex(pageIndex, pageSize), pageSize);
        for (Map<String, Object> m : l) {
            List<Map<String, Object>> modules = authMapper.queryUserAuth(Integer.parseInt(m.get("id") + ""));
            m.put("auths", modules);
            Date expireDate = (Date) m.get("expire_time");
            if (expireDate != null) {
                String ds = sdf.format(expireDate);
                m.put("expire_time", ds);
            }
            //移除密码列,防止前台抓包看密码
            m.remove("password");
        }
        ForePage<Map<String, Object>> f = new ForePage<>(count, pageIndex, l);
        return new Msg(true, "", f);
    }


    /**
     * 用户修改个人信息
     *
     * @param user
     * @return
     */
    public Msg modifyUserInfo(User user) {
        Msg msg = new Msg(true);
        //得到用户信息
        User userInfo = userMapper.queryById(user.getId());
        if (userInfo != null && user != null) {
            userInfo.setRealName(user.getRealName());
            if (!StringUtil.isEmpty(user.getPassword())) {
                userInfo.setPassword(user.getPassword());
            }
            userInfo.setMobilephoneNumber(user.getMobilephoneNumber());
            userMapper.modifyUser(userInfo);
            msg.setMsg("修改成功！");
            msg.setData(userInfo);
            return msg;
        }
        msg.setSuccess(false);
        msg.setMsg("修改失败！");
        return msg;
    }
    /**
     * 根据邮箱查用户
     */
    public Integer findUserByEmail(String email)
    {
        Integer userId = userMapper.findUserByEmail(email);
        return userId;
    }
    /**
     *根据id查询用户
     */
    public User queryById(int id)
    {
        return userMapper.queryById(id);
    }
    /**
     *修改状态
     */
    public void updateStatus(int id)
    {
        userMapper.updateStatus(id);
    }
}
